<?php
class Oa_Util_Db_GlobalDb extends Oa_Util_Db_Base
{
    protected static $_instances;

    protected function __construct(
        $dbName, $dbUser, $dbPwd, $dbReadHost, 
        $dbReadPort, $dbWriteHost, $dbWritePort
    )
    {
        parent::__construct(
            $dbName, $dbUser, $dbPwd, $dbReadHost, 
            $dbReadPort, $dbWriteHost, $dbWritePort
        );
    }
    
    /**
     * 获取global db 对象
     *
     * @param integer $clusterId
     * @param boolean $singleton 是否使用单例模式
     * @return object Oa_Util_Db_GlobalDb
     */
    public static function & getInstance($clusterId, $singleton = true)
    {
        $dbGlobals = Oa_Util_Config::getConfig('db_singles');
        
        if (empty($dbGlobals[$clusterId])) {
            return FALSE;
        }
        
        $dbName = $dbGlobals[$clusterId]['db_name'];
        if (($singleton == true && empty(self::$_instances[$clusterId][$dbName])) || 
            $singleton == false) {
            $phyConfig = Oa_Util_Config::getConfig('db_physical');
            $config = $phyConfig[$dbGlobals[$clusterId]['map']];
            if (isset($config['write']['db_user'])) {
                $dbUser = $config['write']['db_user'];
            } else if (isset($config['db_user'])) {
                $dbUser = $config['db_user'];
            } else {
                $dbUser = $phyConfig['db_user'];
            }
            if (isset($config['write']['db_pwd'])) {
                $dbPwd = $config['write']['db_pwd'];
            } else if (isset($config['db_pwd'])) {
                $dbPwd = $config['db_pwd'];
            } else {
                $dbPwd = $phyConfig['db_pwd'];
            }
            $db = new Oa_Util_Db_GlobalDb(
                $dbName, $dbUser, $dbPwd,
                $config['read']['host'], $config['read']['port'],
                $config['write']['host'], $config['write']['port']
            );
            self::$_instances[$clusterId][$dbName] = &$db;
        }

        return self::$_instances[$clusterId][$dbName];
    }
}
